package com.dq.service.evaluation.impl;

import com.dq.exception.customException.AdminException;
import com.dq.controller.in.OrgTemplateRequest;
import com.dq.vo.Vo;

import com.dq.domain.evaluation.EvaluationTemplateChild;
import com.dq.domain.evaluation.OrgTemplate;
import com.dq.domain.sys.section.SysSection;
import com.dq.repository.BaseRepositories;
import com.dq.service.evaluation.OrgTemplateService;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author luchangtong
 * @Date 2020/3/17 15:08
 */
@Service
public class OrgTemplateServiceImpl extends BaseRepositories implements OrgTemplateService {
    @Override
    public Vo list() throws AdminException {
        SysSection section = sysUserService.getUser().getSection();
        List<OrgTemplate.OrgTemplateVo> orgTemplateVos = new ArrayList<>();
        List<OrgTemplate> orgTemplates = orgTemplateRepository.findByDeletedFalseAndSysDeptOrderByEvaluationTemplateSortAsc(section);
        orgTemplates.forEach(orgTemplate -> {
            orgTemplateVos.add(orgTemplate.toOrgTemplateVo());
        });
        return new Vo(orgTemplateVos);
    }

    @Override
    public Vo saveOrgTemplate(OrgTemplateRequest orgTemplateRequest) throws AdminException {
        SysSection section = sysUserService.getUser().getSection();
        if(orgTemplateRequest.getChildIds().size() == 0){
            throw new AdminException("请先选择");
        }
        List<OrgTemplate> orgTemplates = new ArrayList<>();
        orgTemplateRequest.getChildIds().forEach(aLong -> {
            EvaluationTemplateChild child = dao.get(EvaluationTemplateChild.class,aLong);
            OrgTemplate orgTemplate = new OrgTemplate();
            orgTemplate.setEvaluationTemplateChild(child);
            orgTemplate.setSysDept(section);
            orgTemplate.setEvaluationTemplate(child.getEvaluationTemplate());
            orgTemplates.add(orgTemplate);
        });
        orgTemplateRepository.saveAll(orgTemplates);
        return new Vo(HttpStatus.OK);
    }

    @Override
    public Vo editOrgTemplate(OrgTemplateRequest orgTemplateRequest) throws AdminException {
        delOrgTemplate();
        saveOrgTemplate(orgTemplateRequest);
        return new Vo(HttpStatus.OK);
    }

    @Override
    public Vo delOrgTemplate() throws AdminException {
        SysSection section = sysUserService.getUser().getSection();
        List<OrgTemplate> orgTemplateList = orgTemplateRepository.findByDeletedFalseAndSysDeptOrderByEvaluationTemplateSortAsc(section);
        orgTemplateRepository.deleteAll(orgTemplateList);
        return new Vo(HttpStatus.OK);
    }
}
